from django.shortcuts import render
from django.http import HttpResponse,JsonResponse,Http404
from myadmin import models
from django.contrib.auth.hashers import make_password,check_password

import random,requests
# Create your views here.

#前台首页
def index(request):


    #获取首页的分类列表
    bs=models.Books.objects.all()

    #分配数据
    context={'booktypes':gettypes(),'books':bs}

    #加载模板
    return render(request,'myhome/index.html',context)


#前台列表页
def booklist(request,tid):
    #获取当前分类对象
    t=models.Booktype.objects.get(id=tid)
    #判断当前传递的分类对象是顶级分类还是子类
    if t.pid == 0:
        #获取当前顶级分类下的所有子类
        t.sub=models.Booktype.objects.filter(pid=t.id)
        t.parent=t.name
    else:
        t.sub=models.Booktype.objects.filter(pid=t.pid)
        parent=models.Booktype.objects.get(id=t.pid)
        t.parent=parent.name
    # 分配数据
    context = {'booktypes': gettypes(),'data':t}
    #加载模板
    return render(request,'myhome/list.html',context)

#前台详情页
def detail(request,bid):
    try:
        #根据传递的id获取书籍据信息
        book=models.Books.objects.get(id=bid)

        # 分配数据
        context = {'booktypes': gettypes(),'book':book}
        #加载模板
        return render(request,'myhome/detail.html',context)
    except:
        raise Http404()

def gettypes():
    # 获取首页的分类列表
    ts = models.Booktype.objects.filter(pid=0)
    for x in ts:
        x.sub = models.Booktype.objects.filter(pid=x.id)
    return ts
